//
//  DMMessageCellManager.m
//  HDMainWindow
//
//  Created by apple on 2017/5/5.
//  Copyright © 2017年 com.devin.definesys. All rights reserved.
//

#import "DMMessageCellManager.h"

static DMMessageCellManager *cellManager ;

@interface DMMessageCellManager() {
    // key 是 cell 的类名，value 是 model 的 类名
    NSMutableDictionary *modelWithCell ;
}

@end

@implementation DMMessageCellManager

+(instancetype) sharedInstance {
    if (!cellManager) {
        static dispatch_once_t onceToken;
        dispatch_once(&onceToken, ^{
            cellManager = [[DMMessageCellManager alloc] init];
        });
    }
    return cellManager ;
}

- (DMMessageBaseCell *) cellForBaseModel:(DMMessageBaseModel *) baseModel {
    DMMessageBaseCell *cell = nil ;
    
    for (NSString *cellClass in [self relationModelWithCell]) {
        NSDictionary *model = [self relationModelWithCell][cellClass] ;
        if (model && [NSStringFromClass([baseModel class]) isEqualToString:model[@"modelClass"]] && [baseModel.modelType isEqualToString:model[@"modelType"]]) {
            
            cell = [[NSClassFromString(cellClass) alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellClass];
            
            [baseModel setNeedsUpdateForReuse];
            //设置Model ，执行更新。
            cell.messageModel = baseModel ;
            
            cell.messageModel.cellHeight = [NSClassFromString(cellClass) heightForModel:baseModel];
            break ;
        }
    }
    
    return cell ;
}

- (void) relationModel:(NSString *)modelClass modelType:(NSString *)modelType withCell: (NSString *) cellClass {
    if (!modelWithCell) {
        modelWithCell = [NSMutableDictionary dictionary];
    }
    if (!cellClass || !modelClass) {
        return ;
    }
    [modelWithCell setObject:@{@"modelClass":modelClass,@"modelType":modelType} forKey:cellClass];
}

- (NSDictionary *) relationModelWithCell {
    if (!modelWithCell || modelWithCell.count == 0) {
        [self relationModel:@"DMMessageBaseModel" modelType:@"BASE" withCell:@"DMMessageBaseCell"];
        [self relationModel:@"DMMessageTextModel" modelType:@"TEXT" withCell:@"DMMessageTextCell"];
        [self relationModel:@"DMMessageTimeModel" modelType:@"TIME" withCell:@"DMMessageTimeCell"];
        [self relationModel:@"DMMessageImageModel" modelType:@"IMAGE" withCell:@"DMMessageImageCell"];

    }
    return [NSDictionary dictionaryWithDictionary:modelWithCell];
}

@end
